package diona.dao;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * User: anton
 * Date: 13.03.11 20:17
 */
public class SharedFileDao extends HklDao
{
     private static Logger LOG = LoggerFactory.getLogger(SharedFileDao.class);

    private final String tempPath;

    public SharedFileDao(JdbcTemplate jdbcTemplate, String tempPath)
    {
        super(jdbcTemplate);
        this.tempPath = tempPath;
    }

    public void add(BufferedImage image)
    {
        File file = saveImage(image);
        add(file.getAbsolutePath(), ShareType.IMAGE);
    }

    private File saveImage(BufferedImage image)
    {
        File parent = new File(tempPath);
        if (!parent.exists() && !parent.mkdirs()) {
            throw new RuntimeException("Cannot create directory " + parent.getAbsolutePath());
        }
        File outputFile = new File(parent, UUID.randomUUID().toString() + ".jpg");
        LOG.debug("Saving image to {}", outputFile);
        try {
            ImageIO.write(image, "jpg", outputFile);
        } catch (IOException e) {
            throw new RuntimeException("Cannot write image to file", e);
        }

        return outputFile;
    }

    public void add(String path)
    {
        add(path, ShareType.FILE_PATH);
    }

    private void add(String path, ShareType shareType)
    {
        jdbcTemplate.update("insert into HKL_SHARED_FILES (PATH, WHEN_ADDED, SHARE_TYPE, IS_SENT) values(?, ?, ?, ?)",
                path, new Date(), shareType.code, false);
    }

    public List<SharedItem> getNotSentItems()
    {
        return jdbcTemplate.query("select * from HKL_SHARED_FILES where IS_SENT = ?", new SharedItemRowMapper(), false);
    }

    public void markSent(int id)
    {
        jdbcTemplate.update("update HKL_SHARED_FILES set IS_SENT = ? where ID = ?", true, id);
    }

    public void initDb()
    {
        createTableIfNotExists("HKL_SHARED_FILES",
                "create table HKL_SHARED_FILES (ID IDENTITY, PATH varchar(255) not null, " +
                        "WHEN_ADDED datetime not null, " +
                        "SHARE_TYPE int not null, " +
                        "IS_SENT boolean not null" +
                        ")");
    }

    private class SharedItemRowMapper implements RowMapper<SharedItem>
    {

        public SharedItem mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            return new SharedItem(rs.getInt("ID"), rs.getString("PATH"), new DateTime(rs.getDate("WHEN_ADDED")),
                    rs.getBoolean("IS_SENT"), ShareType.getByCode(rs.getInt("SHARE_TYPE")));
        }
    }

}
